package com.ys.chatserver.http.logic;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.eva.framework.Processor;
import com.eva.framework.dto.SysActionConst;
import com.eva.framework.utils.EndsExceptionFactory;
import com.eva.framework.utils.LoggerFactory;
import com.google.gson.Gson;
import com.ys.chatserver.BaseConf;
import com.ys.chatserver.common.dto.cnst.RetResult;
import com.ys.chatserver.common.dto.cnst.UserProtocalsType;
import com.ys.chatserver.http.logic.dto.Faces;
import com.ys.chatserver.http.logic.dto.HumanFace;
import com.ys.chatserver.http.logic.dto.JobDispatchConst;
import com.ys.chatserver.http.logic.dto.PageData;
import com.ys.chatserver.im.util.MessageHelper;
import com.ys.chatserver.tool.EmptyUtils;
import com.ys.chatserver.tool.IdUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

public class HumanFaceProcessor implements SysActionConst, Processor {


    @Override
    public Object process(int job_dispatch_id, int action_id, Object newData, Object oldData, User user) throws Exception {

        Object ret = null;
        String newDataJSON = (String) newData;

        if (job_dispatch_id == JobDispatchConst.LOGIC_HUMAN_FACE) {
            ret = humanFaceJobDispatcher(action_id, newDataJSON, oldData, user);
        } else {
            throw EndsExceptionFactory.INVALID_JOB_DISPATCHER_ID(job_dispatch_id);
        }
        return ret;
    }

    public String humanFaceJobDispatcher(int action_id, Object newData, Object oldData, User user) throws Exception {
        // 检索备份文件
        JSONObject nwObj = JSONObject.parseObject((String) newData);
        if (action_id == ACTION_ADD_HUMAN_FACE) {
            JSONArray fileName = nwObj.getJSONArray("fileName");
            String username = nwObj.getString("username");
            if (!fileName.isEmpty() || EmptyUtils.isNotEmpty(username)) {
                String idCard = nwObj.getString("idCard");
                Boolean sex = nwObj.getBoolean("sex");
                String info = nwObj.getString("info");
                JSONArray number = nwObj.getJSONArray("number");
                Integer fileType = nwObj.getInteger("fileType");
                StringBuilder builder = new StringBuilder();
                builder.append("insert into human_face_file(id,file_name,username");
                if (EmptyUtils.isNotEmpty(idCard)) {
                    builder.append(",id_card");
                }
                if (Objects.nonNull(sex)) {
                    builder.append(",sex");
                }
                if (EmptyUtils.isNotEmpty(info)) {
                    builder.append(",info");
                }
                if (null != number && !number.isEmpty()) {
                    builder.append(",number");
                }
                builder.append(",file_type");
                builder.append(") values ('").append(IdUtils.get8Uuid()).append("','").append(fileName.toJSONString()).append("','").append(username).append("'");
                if (EmptyUtils.isNotEmpty(idCard)) {
                    builder.append(",'").append(idCard).append("'");
                }
                if (Objects.nonNull(sex)) {
                    builder.append(",").append(sex);
                }
                if (EmptyUtils.isNotEmpty(info)) {
                    builder.append(",'").append(info).append("'");
                }
                if (null != number && !number.isEmpty()) {
                    builder.append(",'").append(number.toJSONString()).append("'");
                }
                if (Objects.nonNull(fileType)) {
                    builder.append(",").append(fileType);
                }else {
                    builder.append(",").append(1);
                }
                builder.append(")");
                boolean result = LogicProcessor2.db.update(Collections.singletonList(builder.toString()), false);
                return result ? new Gson().toJson(RetResult.successResult("成功")) : new Gson().toJson(RetResult.failResult("失败"));
            } else {
                return new Gson().toJson(RetResult.failResult("文件名或者姓名不能为空"));
            }
        } else if (action_id == ACTION_DETAIL_HUMAN_FACE) {
            String id = nwObj.getString("id");
            Vector<Vector<?>> vector = LogicProcessor2.db.queryData("select file_name,username,sex,id_card,info,number from human_face_file where id = '" + id + "'");
            if (!vector.isEmpty()) {
                HumanFace humanFace = new HumanFace();
                vector.forEach(v -> {
                    humanFace.setId(id);
                    if (EmptyUtils.isNotEmpty(v.get(0))) {
                        humanFace.setFileName(JSONArray.parseArray(v.get(0).toString()));
                    }
                    humanFace.setUsername(v.get(1).toString());
                    humanFace.setSex(v.get(2).toString().equals("1"));
                    if (!Objects.isNull(v.get(3))) {
                        humanFace.setIdCard(v.get(3).toString());
                    }
                    if (!Objects.isNull(v.get(4))) {
                        humanFace.setIdCard(v.get(4).toString());
                    }
                    if (EmptyUtils.isNotEmpty(v.get(5))) {
                        humanFace.setNumber(JSONArray.parseArray(v.get(5).toString()));
                    }
                });
                return new Gson().toJson(humanFace);
            }
            return new Gson().toJson(RetResult.failResult("不存在"));
        } else if (action_id == ACTION_DELETE_HUMAN_FACE) {
            String id = nwObj.getString("id");
            Vector<Vector<?>> res = LogicProcessor2.db.queryData("select file_name from human_face_file where id = '" + id + "'");
            if (!res.isEmpty()) {
                JSONArray fileNames = JSONArray.parseArray(res.get(0).get(0).toString());
                fileNames.forEach(fileName -> {
                    String path = BaseConf.getInstance().getDIR_HUMAN_FACE_UPLOAD() + File.separator + fileName;
                    if (FileUtil.exist(path)) {
                        FileUtil.del(path);
                    }
                    String thPath = BaseConf.getInstance().getDIR_HUMAN_FACE_UPLOAD() + File.separator + "th_" + fileName;
                    if (FileUtil.exist(thPath)) {
                        FileUtil.del(thPath);
                    }
                });
            }
            boolean result = LogicProcessor2.db.update(Collections.singletonList("delete from human_face_file where id = '" + id + "'"), false);
            return result ? new Gson().toJson(RetResult.successResult("删除成功")) : new Gson().toJson(RetResult.failResult("不存在"));
        } else if (action_id == ACTION_QUERY_HUMAN_FACE) {
            int pageSize = Integer.parseInt(nwObj.getString("pageSize"));
            int pageNumber = Integer.parseInt(nwObj.getString("pageNumber"));
            String username = nwObj.getString("username");
            String number = nwObj.getString("number");
            Integer fileType = nwObj.getInteger("fileType");
            StringBuilder builder = new StringBuilder();
            builder.append("select id,file_name,username,sex,id_card,info,number,file_type from human_face_file where 1=1 ");
            if (EmptyUtils.isNotEmpty(username)) {
                builder.append(" and username like '%").append(username).append("%'");
            }
            if (EmptyUtils.isNotEmpty(number)) {
                builder.append(" and number like '%").append(number).append("%'");
            }
            if (Objects.nonNull(fileType)) {
                builder.append(" and file_type =").append(fileType);
            }
            if (pageNumber > 0) {
                int pageNum = (pageNumber - 1) * pageSize;
                builder.append(" order by id desc");
                builder.append(" limit ").append(pageNum).append(",").append(pageSize);
            }
            Vector<Vector<?>> res = LogicProcessor2.db.queryData(builder.toString());

            StringBuilder sb = new StringBuilder();
            sb.append("select count(1) from human_face_file where 1=1 ");
            if (EmptyUtils.isNotEmpty(username)) {
                sb.append(" and username like '%").append(username).append("%'");
            }
            if (EmptyUtils.isNotEmpty(number)) {
                sb.append(" and number like '%").append(number).append("%'");
            }
            if (Objects.nonNull(fileType)) {
                sb.append(" and file_type =").append(fileType);
            }
            Vector<Vector<?>> count = LogicProcessor2.db.queryData(sb.toString());
            ArrayList<HumanFace> humanFaces = new ArrayList<>();
            if (!res.isEmpty()) {
                res.forEach(or -> {
                    HumanFace humanFace = new HumanFace();
                    humanFace.setId(or.get(0).toString());
                    humanFace.setFileName(JSONArray.parseArray(or.get(1).toString()));
                    humanFace.setUsername(or.get(2).toString());
                    humanFace.setSex(or.get(3).toString().equals("1"));
                    humanFace.setIdCard(or.get(4).toString());
                    humanFace.setInfo(or.get(5).toString());
                    if (EmptyUtils.isNotEmpty(or.get(6))) {
                        humanFace.setNumber(JSONArray.parseArray(or.get(6).toString()));
                    }
                    humanFace.setFileType(Integer.parseInt(or.get(7).toString()));
                    humanFaces.add(humanFace);
                });
            }

            PageData<HumanFace> pageData = new PageData<>();
            pageData.setRecords(humanFaces);
            pageData.setTotal(Long.parseLong(count.get(0).get(0).toString()));
            pageData.setPageNumber(pageNumber);
            pageData.setPageSize(humanFaces.size());
            return new Gson().toJson(pageData);
        } else if (action_id == ACTION_UPDATE_HUMAN_FACE) {
            String id = nwObj.getString("id");
            Vector<Vector<?>> res = LogicProcessor2.db.queryData("select file_name from human_face_file where id = '" + id + "'");
            JSONArray oldFileNames = JSONArray.parseArray(res.get(0).get(0).toString());
            JSONArray fileNames = nwObj.getJSONArray("fileName");
            oldFileNames.forEach(oldFileName -> {
                if (!fileNames.contains(oldFileName)) {
                    String path = BaseConf.getInstance().getDIR_HUMAN_FACE_UPLOAD() + File.separator + oldFileName;
                    if (FileUtil.exist(path)) {
                        FileUtil.del(path);
                    }
                    String thPath = BaseConf.getInstance().getDIR_HUMAN_FACE_UPLOAD() + File.separator + "th_" + oldFileName;
                    if (FileUtil.exist(thPath)) {
                        FileUtil.del(thPath);
                    }
                }
            });
            String username = nwObj.getString("username");
            if (!fileNames.isEmpty() || EmptyUtils.isNotEmpty(username)) {
                String idCard = nwObj.getString("idCard");
                Boolean sex = nwObj.getBoolean("sex");
                String info = nwObj.getString("info");
                JSONArray number = nwObj.getJSONArray("number");
                StringBuilder builder = new StringBuilder();
                builder.append("update human_face_file set file_name = '").append(fileNames.toJSONString()).append("',username='").append(username).append("'");
                if (EmptyUtils.isNotEmpty(idCard)) {
                    builder.append(",id_card='").append(idCard).append("'");
                }
                if (Objects.nonNull(sex)) {
                    builder.append(",sex=").append(sex);
                }
                if (EmptyUtils.isNotEmpty(info)) {
                    builder.append(",info='").append(info).append("'");
                }
                if (null != number && !number.isEmpty()) {
                    builder.append(",number='").append(number.toJSONString()).append("'");
                }
                builder.append(" where id = '").append(id).append("'");
                boolean result = LogicProcessor2.db.update(Collections.singletonList(builder.toString()), false);
                return result ? new Gson().toJson(RetResult.successResult("修改成功")) : new Gson().toJson(RetResult.failResult("失败"));
            } else {
                return new Gson().toJson(RetResult.failResult("文件名或者姓名不能为空"));
            }
        } else if (action_id == ACTION_BINDING_HUMAN_FACE) {
            JSONArray devId = nwObj.getJSONArray("userIds");
            JSONArray ids = nwObj.getJSONArray("ids");
            String groupId = nwObj.getString("groupId");
            Integer fileType = nwObj.getInteger("fileType");
            LogicProcessor2.db.update(Collections.singletonList("delete from binding where base_id = '" + groupId + "' and user_uid in ('" + devId.stream().map(Object::toString).collect(Collectors.joining("','")) + "')"), false);
            devId.forEach(d -> {
                JSONArray fileNames = new JSONArray();
                ids.forEach(id -> {
                    try {
                        Vector<Vector<?>> res = LogicProcessor2.db.queryData("select if(file_type = 1,file_name,number)as file_name from human_face_file where id = '" + id + "'");
                        String string = res.get(0).get(0).toString();
                        JSONArray objects = JSONArray.parseArray(string);
                        fileNames.addAll(objects);
                        String stringBuilder = "insert into binding (human_face_id,base_id,user_uid)values('" + id + "'," + "'" + groupId + "','" + d + "')";
                        LogicProcessor2.db.update(Collections.singletonList(stringBuilder), false);
                    } catch (Exception e) {
                        LoggerFactory.getLog().error(e.getMessage(), e);
                    }
                });
                try {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("groupId", groupId);
                    jsonObject.put("fileNames", fileNames);
                    jsonObject.put("fileType",fileType);
                    MessageHelper.sendMessage(d.toString(), jsonObject.toString(), false, UserProtocalsType.ACTION_DEVICE_HUMAN_FACE_BIND, null);

                } catch (Exception e) {
                    LoggerFactory.getLog().error(e.getMessage(), e);
                }
            });
            return new Gson().toJson(RetResult.successResult("成功"));
        } else if (action_id == ACTION_LIST_BINGDING) {
            String groupId = nwObj.getString("groupId");
            Integer fileType = nwObj.getInteger("fileType");
            String sql = "select c.user_uid,g.nickname from binding c left join g_users g on g.user_uid = c.user_uid where g.del_flag is false and c.base_id = '" + groupId + "' group by c.user_uid";
            Vector<Vector<?>> vector = LogicProcessor2.db.queryData(sql);
            List<Faces> list = new ArrayList<>();
            if (!vector.isEmpty()) {
                for (Vector<?> v : vector) {
                    Faces faces = new Faces();
                    String userId = v.get(0).toString();
                    String username = v.get(1).toString();
                    faces.setUserame(username);
                    faces.setUserId(userId);
                    String s = "select  g.id,g.username,g.file_name from binding c left join human_face_file g on c.human_face_id = g.id where g.file_type = "+fileType+" and c.base_id = '" + groupId + "' and c.user_uid = '" + userId + "' group by g.id";
                    Vector<Vector<?>> tor = LogicProcessor2.db.queryData(s);
                    if (!tor.isEmpty()) {
                        List<Faces.Face> child = new ArrayList<>();
                        for (Vector<?> ec : tor) {
                            String id = ec.get(0).toString();
                            String facename = ec.get(1).toString();
                            String filename = ec.get(2).toString();
                            Faces.Face face = new Faces.Face();
                            face.setFaceName(facename);
                            face.setId(id);
                            face.setFileNames(JSON.parseArray(filename));
                            child.add(face);
                        }
                        faces.setFaces(child);
                    }
                    list.add(faces);
                }
            }
            return new Gson().toJson(list);
        } else if (action_id == ACTION_QUERY_CURRENT_BINDING_PIC) {
            String groupId = nwObj.getString("groupId");
            Integer fileType = nwObj.getInteger("fileType");
            String userId = user.getUserId();
            JSONArray objects = new JSONArray();
            String s = "select  if(g.file_type = 1,g.file_name,g.number)as file_type from binding c left join human_face_file g on c.human_face_id = g.id where g.file_type = "+fileType+" and  c.base_id = '" + groupId + "' and c.user_uid = '" + userId + "' group by g.id";
            Vector<Vector<?>> tor = LogicProcessor2.db.queryData(s);
            if (!tor.isEmpty()) {
                tor.forEach(a -> {
                    JSONArray array = JSONArray.parseArray(a.get(0).toString());
                    if (!array.isEmpty()) {
                        objects.addAll(array);
                    }
                });
            }
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("groupId", groupId);
            jsonObject.put("fileNames", objects);
            return new Gson().toJson(jsonObject);
        }
        throw EndsExceptionFactory.INVALID_JOB_DISPATCHER_ID(action_id);
    }

}